import axios from 'axios'
import { ElMessageBox, ElMessage } from 'element-plus'
import { showFullScreenLoading, tryHideFullScreenLoading } from '@/config/serviceLoading'
import { getToken } from '@/utils/cookies'
import { useUserStore } from '@/store/modules/user'
export default (config: any) => {
  // 创建axios实例
  const service: any = axios.create({
    baseURL: process.env.VUE_APP_API_GETAWAY,
    // 超时
    timeout: 50000,
  })
  // 请求拦截器
  service.interceptors.request.use(
    (config: any) => {
      // 当前请求不需要显示 loading，在 api 服务中通过指定的第三个参数: { noLoading: true } 来控制
      config.noLoading || showFullScreenLoading()
      config.headers['Authorization'] = getToken() || ''
      config.headers['Content-Type'] = config.headers['Content-Type'] || 'application/json'
      // 8080
      if (config.type == 'file') {
        config.headers['Content-type'] = 'application/multipart/form-data'
      } else if (config.type == 'form') {
        config.headers['Content-type'] = 'application/x-www-form-urlencoded'
      }
      if (config.method && config.method.toLowerCase() === 'get') {
        config.data = true
      }
      return config
    },
    (error: any) => {
      return Promise.reject(error)
    }
  )
  // 响应拦截器
  service.interceptors.response.use(
    (response: any) => {
      const code = response.data.code
      const message = response.data.message
      tryHideFullScreenLoading()
      if (code === 'A0101' || code === 'A0102' || code === 'A0104') {
        ElMessageBox.confirm(`${message || '登录过期，请重新登录'}`, '系统提示', {
          confirmButtonText: '重新登录',
          showCancelButton: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
          showClose: false,
          type: 'error',
        }).then(async () => {
          // 调用退出登录接口
          await useUserStore().FedLogOut()
          window.location.href = '/'
        })
      } else if (code !== '0') {
        if (config.noMessage) {
          return Promise.reject(response.data)
        } else {
          ElMessage({
            message: response.data.message,
            type: 'error',
            duration: 5 * 1000,
          })
          return Promise.reject('error')
        }
      } else {
        return response.data
      }
    },
    (error: any) => {
      tryHideFullScreenLoading()
      ElMessage({
        message: error.message,
        type: 'error',
        duration: 5 * 1000,
      })
      return Promise.reject(error)
    }
  )
  return service(config)
}
